package logic

import (
	"context"
	"fmt"
	"shopping/model/mysql"
	"shopping/model/redis"
	"shopping/pkg"

	"shopping/shoppingrpc/internal/svc"
	"shopping/shoppingrpc/shoppingrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserUpdateLogic {
	return &UserUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserUpdateLogic) UserUpdate(in *shoppingrpc.UserUpdateRequest) (*shoppingrpc.UserUpdateResponse, error) {
	// todo: add your logic here and delete this line
	get := redis.Client.Get("Smsupdate" + in.Phone)
	if get.Val() != in.Sms {
		return nil, fmt.Errorf("当前验证码错误")
	}
	var find mysql.User
	mysql.DB.Debug().Where("phone =?", in.Phone).Find(&find)
	if find.ID == 0 {
		return nil, fmt.Errorf("当前账号未注册")
	}
	if find.Password != pkg.MdePassword(in.Oldpassword) {
		return nil, fmt.Errorf("旧密码不正确")
	}
	if find.Password == pkg.MdePassword(in.Password) {
		return nil, fmt.Errorf("新旧密码不能一致")
	}
	if pkg.MdePassword(in.Password) != pkg.MdePassword(in.Newpassword) {
		return nil, fmt.Errorf("确认新密码错误")
	}
	find.Password = pkg.MdePassword(in.Newpassword)
	mysql.DB.Debug().Updates(&find)
	redis.Client.Del("Smsupdate" + in.Phone)
	return &shoppingrpc.UserUpdateResponse{Id: int64(find.ID)}, nil
}
